package com.leo.reconsume.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.consumer.rebalance.AllocateMessageQueueAveragely;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

public class MyConsumerOrderly {
    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_08_01");
        consumer.setNamesrvAddr("localhost:9876");


        // 设置负载均衡算法
        consumer.setAllocateMessageQueueStrategy(new AllocateMessageQueueAveragely());
        // 消费的模式：集群
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 消费的模式：广播
        //consumer.setMessageModel(MessageModel.BROADCASTING);

        // 设置消费者的线程数
        consumer.setConsumeThreadMin(1);
        consumer.setConsumeThreadMax(10);


        // 设置消息重试次数, 16个级别（广播模式无效, 有序消息会不断重试，间隔1秒，会阻塞后续消息的消费）
        consumer.setMaxReconsumeTimes(5);
        // 设置消息批处理的一个批次中消息的最大个数, 一次获取一条消息
        consumer.setConsumeMessageBatchMaxSize(1);

        // 订阅主题
        consumer.subscribe("tp_demo_08", "*");

        // 顺序消费
        consumer.setMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {

                for (MessageExt msg : msgs) {
                    System.out.println(msg.getMsgId() + "\t" + msg.getQueueId() + "\t" + new String(msg.getBody()));
                }

                //return ConsumeOrderlyStatus.SUCCESS;  // 确认消息
                //return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT; // 引发重试
                return null; // 引发重试
            }
        });


        consumer.start();
    }
}